package com.huidu.bitrade.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huidu.bitrade.constant.SystemConfigConstants;
import com.huidu.bitrade.constant.TransactionType;
import com.huidu.bitrade.entity.Activity;
import com.huidu.bitrade.entity.ActivityHdzOrder;
import com.huidu.bitrade.entity.MemberTransaction;
import com.huidu.bitrade.entity.MemberWallet;
import com.huidu.bitrade.mapper.ActivityHdzOrderMapper;
import com.huidu.bitrade.mapper.SystemConfigMapper;
import com.huidu.bitrade.service.ActivityHdzOrderService;
import com.huidu.bitrade.service.ActivityService;
import com.huidu.bitrade.service.MemberTransactionService;
import com.huidu.bitrade.service.MemberWalletService;
import com.huidu.bitrade.util.DateUtil;
import com.huidu.bitrade.util.MessageResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.Objects;

@Service
@Slf4j
@RequiredArgsConstructor
public class ActivityHdzOrderServiceImpl extends ServiceImpl<ActivityHdzOrderMapper, ActivityHdzOrder> implements ActivityHdzOrderService {

    private final RestTemplate restTemplate;
    private final MemberWalletService memberWalletService;
    private final ActivityService activityService;
    private final MemberTransactionService memberTransactionService;
    private final ActivityHdzOrderMapper activityHdzOrderMapper;
    private final SystemConfigMapper systemConfigMapper;
    /**
     * 立即赎回
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void redeemOrder(Long id){
        //查询订单，计算订单赎回手续费率
        ActivityHdzOrder activityHdzOrder = getById(id);
        //查询手续费率
        BigDecimal redeem = getConfigRedeem(activityHdzOrder.getCreateTime());
        //修改钱包余额
        MemberWallet memberWallet = memberWalletService.findByCoinUnitAndMemberId(activityHdzOrder.getSymbol(), activityHdzOrder.getMemberId());
        if(Objects.isNull(memberWallet)){
            throw new IllegalArgumentException("未找到用户钱包");
        }
        //计算收益百分比
        BigDecimal rate = BigDecimal.valueOf(100).subtract(redeem).divide(BigDecimal.valueOf(100),2,RoundingMode.DOWN);
        //计算最后所得
        BigDecimal price = activityHdzOrder.getNumber().multiply(rate).setScale(8, RoundingMode.DOWN);
//        if(activityHdzOrder.getStatus()==1){
//            int row = memberWalletService.decreaseToRelease(memberWallet.getId(),activityHdzOrder.getCurrentNumber());
//            if(row<1){
//                log.info("==========需要扣除torelease钱包========memberId:{},price:{}",activityHdzOrder.getMemberId(),activityHdzOrder.getCurrentNumber());
//                throw new IllegalArgumentException("扣除用户torelease钱包异常");
//            }
//        }
        int row1 = memberWalletService.increaseBalance(memberWallet.getId(),price);
        if(row1<1){
            log.info("==========需要增加hdz钱包余额========memberId:{},price:{}",activityHdzOrder.getMemberId(),price);
            throw new IllegalArgumentException("增加用户hdz余额异常");
        }
        //修改订单状态
        activityHdzOrder.setStatus(2);//赎回
        activityHdzOrder.setRedeemTime(LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli());//赎回时间
        updateById(activityHdzOrder);
    }

    /**
     * 获取赎回费率%
     *
     * @param time 时间
     * @return
     */
    @Override
    public BigDecimal getConfigRedeem(Long time){
        LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()); // 将Instant对象转换为LocalDateTime对象
        long years = dateTime.until(LocalDateTime.now(), ChronoUnit.YEARS);
        String string = "";
        switch ((int) years){
            case 0://不满一年
                string = SystemConfigConstants.HDZ_INTEREST_UN_YEAR;
                break;
            case 1://一年
                string = SystemConfigConstants.HDZ_INTEREST_ONE_YEAR;
                break;
            case 2://两年
                string = SystemConfigConstants.HDZ_INTEREST_TWO_YEAR;
                break;
            case 3://三年
                string = SystemConfigConstants.HDZ_INTEREST_THREE_YEAR;
                break;
        }
        return new BigDecimal(systemConfigMapper.getConfigValue(string));
    }

    /**
     * 用户参与质押
     * @param memberId 用户id
     * @param amount 数量
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MessageResult pledge(Long memberId, BigDecimal amount,Long activityId){
        MessageResult messageResult = MessageResult.success("恭喜！认购成功！");
        Activity activity = activityService.findById(activityId);
        //创建订单，扣除余额
        save(ActivityHdzOrder.builder()
                .memberId(memberId)
                .activityId(activity.getId())
                .number(amount)
                .symbol(activity.getAcceptUnit())
                .status(0)
                .currentNumber(amount)
                .build());
       MemberWallet memberWallet = memberWalletService.findByCoinUnitAndMemberId(activity.getAcceptUnit(),memberId);
       int row = memberWalletService.deductBalance(memberWallet,amount);
       if(row!=1){
           messageResult = MessageResult.error(500,"参与质押扣除余额失败");
       }
       //奖励直推推荐人
        Long inviterId = activityHdzOrderMapper.selectDirectReferrer(memberId);
        if(Objects.nonNull(inviterId)){
            //购买hdz的百分之五，奖励给参与过质押的推荐人
            awardInviter(inviterId,amount,activity.getAcceptUnit());
        }
        //添加流水
        MemberTransaction memberTransaction1 = new MemberTransaction();
        memberTransaction1.setFee(BigDecimal.ZERO);
        memberTransaction1.setAmount(amount);
        memberTransaction1.setMemberId(memberId);
        memberTransaction1.setSymbol(activity.getAcceptUnit());
        memberTransaction1.setType(TransactionType.STAKING_HDZ);
        memberTransaction1.setCreateTime(DateUtil.getCurrentDate());
        memberTransaction1.setRealFee("0");
        memberTransaction1.setDiscountFee("0");
        memberTransactionService.save(memberTransaction1);
        return messageResult;
    }

    /**
     * 奖励直推推荐人
     */
    private void awardInviter(Long inviterId,BigDecimal amount,String unit){
        //购买hdz的百分之五，奖励给参与过质押的推荐人
        BigDecimal price = amount.multiply(BigDecimal.valueOf(0.05)).setScale(8,RoundingMode.DOWN);
        MemberWallet inviterWallet = memberWalletService.findByCoinUnitAndMemberId(unit,inviterId);
        int row = memberWalletService.increaseBalance(inviterWallet.getId(),price);
        if(row!=1){
            log.info("=============质押挖矿：奖励推荐人执行失败，行数不为1=========");
            return;
        }
        //添加流水
        MemberTransaction memberTransaction1 = new MemberTransaction();
        memberTransaction1.setFee(BigDecimal.ZERO);
        memberTransaction1.setAmount(price);
        memberTransaction1.setMemberId(inviterId);
        memberTransaction1.setSymbol(unit);
        memberTransaction1.setType(TransactionType.STAKING_HDZ_AWARD);
        memberTransaction1.setCreateTime(DateUtil.getCurrentDate());
        memberTransaction1.setRealFee("0");
        memberTransaction1.setDiscountFee("0");
        memberTransactionService.save(memberTransaction1);
    }
}
